package com.dtzhejiang.social.supervision.risk.engine.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 *@Autor: yuweiwen
 * @Date:2020/1/6 17:28
 */
@Slf4j
public class LatitudeUtils {
    public static final String KEY_1 = "Xz0HZo5F7YXkThpPHy7c4l2t1KoZ0zuP";

    public static Map getGeocoderLatitude(String address,String city) {
        BufferedReader in = null;
        try {
            // 将地址转换成utf-8的16进制
            address = URLEncoder.encode(address.replaceAll("（.*?）", "").replaceAll("\\(.*?\\)", ""), "UTF-8");
            URL tirc=null;
            if(StringUtils.isNotBlank(city)){
                tirc= new URL("http://api.map.baidu.com/geocoder?address="+ address +"&output=json&key="+ KEY_1+"&city="+city);
            }else{
                tirc= new URL("http://api.map.baidu.com/geocoder?address="+ address +"&output=json&key="+ KEY_1);
            }

            in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
            String res;
            StringBuilder sb = new StringBuilder("");
            while ((res = in.readLine()) != null) {
                sb.append(res.trim());
            }
            String str = sb.toString();
            Map map = null;
            if (StringUtils.isNotEmpty(str)) {
                int lngStart = str.indexOf("lng\":");
                int lngEnd = str.indexOf(",\"lat");
                int latEnd = str.indexOf("},\"precise");
                if (lngStart > 0 && lngEnd > 0 && latEnd > 0) {
                    String lng = str.substring(lngStart + 5, lngEnd);
                    String lat = str.substring(lngEnd + 7, latEnd);
                    map = new HashMap();
                    map.put("lng", lng);
                    map.put("lat", lat);
                    return map;
                }
            }
        } catch (Exception e) {
          log.info("获取失败：{}",address);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
            }
        }
        return null;
    }


    /**
     * 计算经纬度的距离
     * @param gpsFrom
     * @param gpsTo
     * @param ellipsoid
     * @return
     */
    public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid)
    {
        //创建GeodeticCalculator，调用计算方法，传入坐标系、经纬度用于计算距离
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);

        return geoCurve.getEllipsoidalDistance();
    }


    /**
     * 计算两个经纬度之前的距离 单位是米 精确到小数点两位
     * @param fromLatitude
     * @param fromLongitude
     * @param toLatitude
     * @param toLongitude
     * @return
     */
    public static double getDistanceMeterByLatitudeLongitude(double fromLatitude,double fromLongitude,double toLatitude,double toLongitude)
    {
        GlobalCoordinates source = new GlobalCoordinates(fromLatitude, fromLongitude);
        GlobalCoordinates target = new GlobalCoordinates(toLatitude, toLongitude);
        BigDecimal distance = new BigDecimal(getDistanceMeter(source, target, Ellipsoid.Sphere)).setScale(2, RoundingMode.UP);
        return  distance.doubleValue();
    }
}




